package com.xcexample.electronicclasscard.main

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.GsonBuilder
import com.tencent.mmkv.MMKV
import com.xcexample.eightclasscard.main.AutoCloseBean
import com.xcexample.electronicclasscard.GlideHelper
import com.xcexample.electronicclasscard.R
import com.xcexample.electronicclasscard.WeekAdapter
import com.xcexample.electronicclasscard.databinding.ActivityMainBinding
import com.xcexample.electronicclasscard.kaoqin.WorkHistoryFragment
import com.xcexample.electronicclasscard.log.LogUtils
import com.xcexample.electronicclasscard.login.*
import com.xcexample.electronicclasscard.net.ApiFactory
import com.xcexample.electronicclasscard.net.BaseURL
import com.xcexample.electronicclasscard.view.UpdateVersionDialog
import com.ys.rkapi.MyManager
import okhttp3.ResponseBody
import org.json.JSONException
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    val dutyAdapter by lazy {
        DutyAdapter()
    }
    val classAdapter by lazy {
        ClassAdapter()
    }
    val weekAdapter by lazy {
        WeekAdapter()
    }
    val updateVersionDialog by lazy {
        UpdateVersionDialog(this@MainActivity)
    }
    var localName = ""
    private val handler: Handler = Handler()
    private val loopRunnable: Runnable = object : Runnable {
        override fun run() {
            getHomeData()
            if (!hasPermissions(
                    this@MainActivity, arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    )
                )
            ) {
                ActivityCompat.requestPermissions(
                    this@MainActivity,
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ),
                    4
                )
            } else {
                updateApp()
            }
            handler.postDelayed(this, 300000) // 每隔1000毫秒（1秒）执行
        }
    }

    fun write_sys_fs(sys_fs: String?, value: Int) {
        var mode = "1"
        try {
            if (value == 0) mode = "0"
            val fops = FileOutputStream(sys_fs)
            fops.write(mode.toByteArray())
            fops.flush()
            fops.close()
        } catch (e: FileNotFoundException) {
            Log.d("err", "found error")
        } catch (e: IOException) {
            Log.d("err", "IO error")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        val intent = Intent("android.intent.action.hidebar")
        sendBroadcast(intent)
        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        write_sys_fs("/proc/wdt", 0)

        val packageManager = packageManager
        val packageInfo = packageManager.getPackageInfo(packageName, 0)
        localName = packageInfo.versionName

        binding.version.text = "V$localName"

        binding.ring.setRingStrokeWidth(40)
        binding.ring.initPaint("#3F53E0", "#3EC7D3", "#59BBEF")



        binding.rvDuty.adapter = dutyAdapter

        binding.rg.adapter = weekAdapter
        weekAdapter.setOnItemClickListener { adapter, view, position ->
            weekAdapter.select = position
            weekAdapter.notifyDataSetChanged()
            classAdapter.setList(weekAdapter.data[position].list)
        }

        binding.rvClass.layoutManager = GridLayoutManager(this, 4)
        binding.rvClass.adapter = classAdapter

        binding.ivJumpLogin.setOnLongClickListener {
            var token = MMKV.defaultMMKV().decodeString("token")
            if (token.isNullOrEmpty()) {
                LoginFragment {
                    if (it.isNullOrEmpty()) {
                        startActivity(Intent(this, MainActivity::class.java))
                        finish()
                        return@LoginFragment
                    }
                    getHomeData()

                }.show(supportFragmentManager, "")
            }

            true
        }

        binding.ivClass.setOnLongClickListener {
            var token = MMKV.defaultMMKV().decodeString("token")
            if (!token.isNullOrEmpty()) {
                LogoutFragment {}.show(supportFragmentManager, "")
            }
            true
        }

        binding.login.setOnClickListener {
            MMKV.defaultMMKV().clear()
            LoginFragment {
                if (it.isNullOrEmpty()) {
                    startActivity(Intent(this, MainActivity::class.java))
                    finish()
                    return@LoginFragment
                }
                getHomeData()
            }.show(supportFragmentManager, "")
        }
        if (MMKV.defaultMMKV().decodeString("token").isNullOrEmpty()) {
            LoginFragment {
                if (it.isNullOrEmpty()) {
                    startActivity(Intent(this, MainActivity::class.java))
                    finish()
                    return@LoginFragment
                }
                getHomeData()
            }.show(supportFragmentManager, "")
        } else {
            getHomeData()
        }
        handler.post(loopRunnable)

        binding.tvTime.text = getHM()
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_TIME_TICK)
        registerReceiver(receiver, filter)

        binding.cPre.setOnClickListener {
            if (classNoticePage == 1) {
                ToastUtils.showShort("没有上一页了哦")
                return@setOnClickListener
            }
            classNoticePage -= 1
            getClassNotice()
        }
        binding.cNext.setOnClickListener {
            if (cLastPage == classNoticePage) {
                ToastUtils.showShort("没有下一页了哦")
                return@setOnClickListener
            }
            classNoticePage += 1
            getClassNotice()
        }

        binding.sPre.setOnClickListener {
            if (schoolNoticePage == 1) {
                ToastUtils.showShort("没有上一页了哦")
                return@setOnClickListener
            }
            schoolNoticePage -= 1
            getSchoolNotice()
        }
        binding.sNext.setOnClickListener {
            if (sLastPage == schoolNoticePage) {
                ToastUtils.showShort("没有下一页了哦")
                return@setOnClickListener
            }
            schoolNoticePage += 1
            getSchoolNotice()
        }
        if (!hasPermissions(this, PERMISSIONS_ALL)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_ALL, all)
        }
    }

    override fun onDestroy() {
        val intent = Intent("android.intent.action.showbar")
        sendBroadcast(intent)
        handler.removeCallbacks(loopRunnable)
        super.onDestroy()
    }

    var schoolNoticePage = 1
    var classNoticePage = 1
    var retry = 0

    private fun getHomeData() {
        if (MMKV.defaultMMKV().decodeString("token").isNullOrEmpty()) return

        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.getHome()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (json.isNullOrEmpty()) return
                try {
                    val gson = GsonBuilder().create()
                    val obj = gson.fromJson(json, HomeBean::class.java)
                    LogUtils.e("result:$obj")
                    if (obj.code == 0) {
                        var result = obj.data
                        GlideHelper.loadCircleImage(
                            this@MainActivity,
                            binding.ivJumpLogin,
                            result?.schoole_img ?: "",
                            R.mipmap.default_school
                        )
                        GlideHelper.loadCircleImage(
                            this@MainActivity,
                            binding.ivClass,
                            result?.`class`?.class_img ?: "",
                            R.mipmap.default_class
                        )
                        binding.tvClassName.text = result?.`class`?.class_name ?: ""
                        binding.tvSchoolName.text = result?.schoole_name ?: ""
                        binding.room.text = result?.course?.room ?: ""
                        binding.curWeek.text = "当前周次：第 ${result?.course?.cur_week} 周"
                        binding.tvClassTeacher.text =
                            if (result?.`class`?.teacher.isNullOrEmpty()) {
                                "未设置"
                            } else {
                                "${result?.`class`?.teacher}"
                            }
                        binding.tvClassKouhao.text = if (result?.`class`?.kouhao.isNullOrEmpty()) {
                            "未设置"
                        } else {
                            "${result?.`class`?.kouhao}"
                        }
                        binding.tvClassTarget.text = if (result?.`class`?.target.isNullOrEmpty()) {
                            "未设置"
                        } else {
                            "${result?.`class`?.target}"
                        }
                        binding.tvClassGeyan.text = if (result?.`class`?.geyan.isNullOrEmpty()) {
                            "未设置"
                        } else {
                            "${result?.`class`?.geyan}"
                        }

                        var total = result?.kaoqin?.total ?: 0
                        val spannableString =
                            SpannableString("班级总人数：$total 人")
                        val colorSpan = ForegroundColorSpan(Color.parseColor("#3F8CFF"))
                        spannableString.setSpan(
                            colorSpan,
                            5,
                            spannableString.length - 2,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        binding.tvStudentTotal.text = spannableString

                        var lack = result?.kaoqin?.lack ?: 0
                        setSpanBold("缺勤 $lack 人", binding.lack)
                        var shidao = result?.kaoqin?.shidao ?: 0
                        setSpanBold("实到 $shidao 人", binding.shidao)

                        if (total != 0) {
                            if (total > 360) {
                                var i2 = 360.0 / (360.0 % total)
                                binding.ring.setAnglesData(
                                    "${shidao * i2}",
                                    "${lack * i2}",
                                )

                            } else {
                                var i2 = 360.0 / total
                                binding.ring.setAnglesData(
                                    "${shidao * i2}",
                                    "${lack * i2}",
                                )

                            }
                        }


                        binding.ring.showViewWithoutAnimation()


                        binding.present.text = "${result?.kaoqin?.shidao_rate}"

                        var duty = result?.duty ?: arrayListOf()
                        dutyAdapter.data.clear()
                        dutyAdapter.data.addAll(duty)
                        dutyAdapter.notifyDataSetChanged()

                        binding.rg.layoutManager =
                            GridLayoutManager(this@MainActivity, result?.course?.list?.size ?: 0)
                        weekAdapter.setList(result?.course?.list)

                        val calendar = Calendar.getInstance()
                        val dayOfWeek = calendar[Calendar.DAY_OF_WEEK]
                        val adjustedDayOfWeek =
                            if (dayOfWeek === Calendar.SUNDAY) 7 else dayOfWeek - 1

                        Log.e("onSuccess: ", "${dayOfWeek}  ---${adjustedDayOfWeek}")
                        if (weekAdapter.data.size >= adjustedDayOfWeek) {
                            weekAdapter.select = adjustedDayOfWeek - 1
                            classAdapter.setList(weekAdapter.data[adjustedDayOfWeek - 1].list)
                        }
                    } else {
                        if (obj.code == 401) {

                            autoLogin()


                        }
                        Toast.makeText(this@MainActivity, obj.msg, Toast.LENGTH_SHORT)
                            .show()
                    }

                } catch (e: JSONException) {
                    e.printStackTrace()
                }

            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {
                if (retry < 10) {
                    retry++
                    getHomeData()
                } else {
                    retry = 0
                }
            }
        })

        getClassNotice()
        getSchoolNotice()
//        getLocation()
        autoConfig()
        updateOnline(DeviceUtils.getMacAddress())
    }

    private fun autoLogin() {
        val defaultMMKV = MMKV.defaultMMKV()
        defaultMMKV.encode("token", "")
        var account = defaultMMKV.decodeString("account", "")
        var pass = defaultMMKV.decodeString("pass", "")
        var retrofit = ApiFactory.create(BaseURL, false)
        var call = retrofit.loginByPwd(account, pass, "")
        call!!.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                try {
                    val gson = GsonBuilder().create()
                    val obj = gson.fromJson(json, LoginResponse::class.java)
                    LogUtils.e("result:$obj")
                    if (obj.code == 0) {
                        var fromJson =
                            gson.fromJson(
                                obj?.data.toString(),
                                LoginResponseData::class.java
                            )
                        val defaultMMKV = MMKV.defaultMMKV()
                        defaultMMKV.encode("token", fromJson?.access_token)
                        defaultMMKV.encode("account", account)
                        defaultMMKV.encode("pass", pass)
                        getHomeData()

                    } else {
                        Toast.makeText(
                            this@MainActivity,
                            obj.msg,
                            Toast.LENGTH_SHORT
                        )
                            .show()
                    }

                } catch (e: JSONException) {
                    e.printStackTrace()
                }

            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })
    }

    private fun autoConfig() {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.autoConfig()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, AutoCloseBean::class.java)
                        LogUtils.e("result:$obj")

                        if (obj.code == 0) {
                            var result = obj.data
                            if (result.enable == 1) {
                                val calendar = Calendar.getInstance()
                                val year = calendar[Calendar.YEAR]
                                val month = calendar[Calendar.MONTH] + 1
                                val day = calendar[Calendar.DAY_OF_MONTH]
                                val getDayOfWeek = calendar[Calendar.DAY_OF_WEEK]
                                LogUtils.e("getDayOfWeek:$year$month$day$getDayOfWeek")
                                /**
                                 * 接下来要关机的时间，和后面要去开机的时间,当前时间<关机时间<开机时间
                                 * 1、设备开机自启动软件
                                 * 2、班牌软件版本强制升级
                                 * 3、定时开关机/自动开关机。
                                 * 周一是2，周二是3，周三是4，周四是5，周五是6，周六是7，周日是1
                                 */
                                //result:[3,2,4,5,6,1]
                                val contains = result.week.contains(getDayOfWeek)
                                val onTime = result.on_time.split(":")
                                val offTime = result.off_time.split(":")

                                var onHour = 0
                                var onMinute = 0
                                var onSecond = 0

                                var offHour = 0
                                var offMinute = 0
                                var offSecond = 0
                                onTime.forEachIndexed { index, s ->
                                    when (index) {
                                        0 -> onHour = s.toInt()
                                        1 -> onMinute = s.toInt()
                                        2 -> onSecond = s.toInt()
                                    }
                                }
                                offTime.forEachIndexed { index, s ->
                                    when (index) {
                                        0 -> offHour = s.toInt()
                                        1 -> offMinute = s.toInt()
                                        2 -> offSecond = s.toInt()
                                    }
                                }

                                /**
                                 * 如果contains 说明今天要关机，然后我要去寻找开机的时间
                                 *
                                 */
                                if (contains) {
                                    var onCalendar: Calendar? = null
                                    for (i in 1..6) {
                                        var cOn = Calendar.getInstance()
                                        cOn.add(Calendar.DATE, i)
                                        val getDayOfWeek = cOn[Calendar.DAY_OF_WEEK]
                                        if (result.week.contains(getDayOfWeek)) {
                                            onCalendar = cOn
                                            break
                                        }
                                    }

                                    if (onCalendar != null) {
                                        val timeon = intArrayOf(
                                            onCalendar[Calendar.YEAR],
                                            onCalendar[Calendar.MONTH] + 1,
                                            onCalendar[Calendar.DAY_OF_MONTH],
                                            onHour,
                                            onMinute,
                                            onSecond
                                        ) //开机时间

                                        runOnUiThread {
                                            val poweronoff =
                                                Intent("android.intent.action.setpoweronoff")
                                            poweronoff.putExtra("timeon", timeon)
                                            val timeoff = intArrayOf(
                                                year, month, day, offHour, offMinute, offSecond
                                            ) //关机时间

                                            poweronoff.putExtra("timeoff", timeoff)
                                            poweronoff.putExtra("enable", true)
                                            sendBroadcast(poweronoff)

                                            LogUtils.e("关机时间：${timeoff[0]}-${timeoff[1]}-${timeoff[2]} ${timeoff[3]}:${timeoff[4]}:${timeoff[5]}\n开机时间：${timeon[0]}-${timeon[1]}-${timeon[2]} ${timeon[3]}:${timeon[4]}:${timeon[5]}")
                                        }
                                    }

                                }

                            }
                        } else {
                            Toast.makeText(this@MainActivity, obj.msg, Toast.LENGTH_SHORT)
                                .show()
                        }

                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })

    }

    var cLastPage = 0
    private fun getClassNotice() {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.getClassNotice("$classNoticePage")
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, SchoolNoticeBean::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {
                            var result = obj.data
                            cLastPage = result?.last_page ?: 0
                            if (result.total == 0) {
                                binding.linC.visibility = View.INVISIBLE
                                binding.linContent.visibility = View.INVISIBLE
                                binding.emptyC.visibility = View.VISIBLE
                            } else {
                                binding.linC.visibility = View.VISIBLE
                                binding.linContent.visibility = View.VISIBLE
                                binding.emptyC.visibility = View.GONE
                            }
                            binding.cCurrent.text = "$classNoticePage / ${result?.total}"
                            if (result?.data?.isNotEmpty() == true) {
                                var first = result.data.first()
                                binding.cTitle.text = first?.title
                                binding.cName.text = first?.username
                                binding.cTime.text = first?.release_time
                                binding.cContent.text = first.content
                                if (first.imgs is String) {
                                    GlideHelper.loadImage(binding.ivC, first.imgs.toString())
                                } else {
                                    var strings = first.imgs as ArrayList<String>
                                    GlideHelper.loadImage(binding.ivC, strings.first())

                                }
                            }
                        } else {
                            Toast.makeText(this@MainActivity, obj.msg, Toast.LENGTH_SHORT)
                                .show()
                        }

                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })

    }

    var accessKeyId = ""
    var accessKeySecret = ""
    private fun getTST() {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.getTST()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, TSTBean::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {
                            var result = obj.data
                            accessKeyId = result.accessKeyId
                            accessKeySecret = result.accessKeySecret
                            DoorFragment(
                                accessKeyId,
                                accessKeySecret,
                                "${result.securityToken}"
                            ) {
                                try {
                                    MyManager.getInstance(this@MainActivity).gpio1 = "0"
                                } catch (e: Exception) {

                                }
                            }.show(
                                supportFragmentManager,
                                ""
                            )
                        } else {
                            Toast.makeText(this@MainActivity, obj.msg, Toast.LENGTH_SHORT)
                                .show()
                        }

                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })

    }

    private fun updateOnline(mac: String) {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.online(mac)
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, LoginResponse::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {

                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })


    }

    private fun updateApp() {

        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.appUpdate()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, UpdateResponse::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {
                            var version = obj.data?.version
                            var local = localName.split(".")
                            var remote = version?.split(".") ?: arrayListOf()
                            Log.e("local: ", "${local}")
                            Log.e("remote: ", "${remote}")
                            remote.forEachIndexed { index, s ->
                                if (local.size > index) {
                                    var compareTo = s.toInt().compareTo(local[index].toInt())
                                    Log.e("compareTo: ", "${compareTo}")
                                    if (compareTo > 0) {
                                        obj.data?.let { showUpdateDialog(it) }
                                        return
                                    }
                                }
                            }

                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })


    }

    private fun showUpdateDialog(updateBean: AppUpdateData) {
        var build = updateVersionDialog.setVersionName("更新版本 V" + updateBean.version)
            .setApk_url(updateBean.apk)
            .setUpdateContent(updateBean.describe).setNotUpdateText("暂不更新")
            .setUpdateText("立即更新")
            .setNotUpdateOnClickListener { view -> }
            .setUpdateOnClickListener { view ->
            }.build()
        if (build?.isShowing == false)
            build.show()
    }

    private fun getLocation() {
        var retrofit = ApiFactory.create("https://restapi.amap.com/", false)
        var call = retrofit.getLocation()
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (json.isNullOrEmpty()) return
                try {
                    val gson = GsonBuilder().create()
                    val obj = gson.fromJson(json, LocationBean::class.java)
                    LogUtils.e("result:$obj")
                    if (obj.status == "1") {
                        var adcode = obj.adcode
                        getWind(adcode)
                    } else {
                        Toast.makeText(
                            this@MainActivity,
                            "获取当前地区失败，请稍后重试",
                            Toast.LENGTH_SHORT
                        )
                            .show()
                    }

                } catch (e: JSONException) {
                    e.printStackTrace()
                }

            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })

    }

    private fun getWind(adcode: String) {

        var retrofit = ApiFactory.create("https://restapi.amap.com/", false)
        //可选值：base/all
        //
        //base:返回实况天气
        //
        //all:返回预报天气
        var call = retrofit.getWind(adcode, "d3b5b4d6e39abe62da8af86449e8be24", "base")
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, WindBean::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.status == "1") {
                            if (obj?.lives?.isNotEmpty() == true) {
                                var weather = obj.lives[0].weather
                                when (weather) {
                                    "晴", "热" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.sun)
                                    }

                                    "有风", "平静", "微风", "和风", "清风", "强风/劲风", "疾风", "大风", "烈风", "风暴", "狂爆风", "飓风", "热带风暴", "龙卷风" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.wind)
                                    }

                                    "少云", "晴间多云", "多云" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.cloud)
                                    }

                                    "雪", "阵雪", "小雪", "中雪", "大雪", "暴雪", "小雪-中雪", "中雪-大雪", "大雪-暴雪", "冷" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.snow)
                                    }

                                    "浮尘", "扬沙", "沙尘暴", "强沙尘暴", "雾", "浓雾", "强浓雾", "轻雾", "大雾", "特强浓雾" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.fog)
                                    }

                                    "雨雪天气", "雨夹雪", "阵雨夹雪" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.cloud_snow)
                                    }

                                    "阴", "霾", "中度霾", "重度霾", "严重霾", "未知" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.yin)
                                    }

                                    "阵雨", "雷阵雨", "雷阵雨并伴有冰雹", "小雨", "中雨", "大雨", "暴雨", "大暴雨", "特大暴雨", "强阵雨", "强雷阵雨", "极端降雨", "毛毛雨/细雨", "雨", "小雨-中雨", "中雨-大雨", "大雨-暴雨", "暴雨-大暴雨", "大暴雨-特大暴雨", "冻雨" -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.rain)
                                    }

                                    else -> {
                                        binding.ivWind.background =
                                            resources.getDrawable(R.drawable.yin)
                                    }
                                }
                            }
                        } else {
                            Toast.makeText(
                                this@MainActivity,
                                "获取当前地区失败，请稍后重试",
                                Toast.LENGTH_SHORT
                            )
                                .show()
                        }

                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })

    }

    var sLastPage = 0
    private fun getSchoolNotice() {
        var retrofit = ApiFactory.create(BaseURL, true)
        var call = retrofit.getSchoolNotice("$schoolNoticePage")
        call.enqueue(object : Callback<ResponseBody?> {
            override fun onResponse(
                call: Call<ResponseBody?>,
                response: Response<ResponseBody?>
            ) {
                val json = response.body()?.string()
                if (!json.isNullOrEmpty()) {
                    try {
                        val gson = GsonBuilder().create()
                        val obj = gson.fromJson(json, SchoolNoticeBean::class.java)
                        LogUtils.e("result:$obj")
                        if (obj.code == 0) {
                            var result = obj.data
                            sLastPage = result?.last_page ?: 0

                            if (result.total == 0) {
                                binding.linContentS.visibility = View.INVISIBLE
                                binding.linS.visibility = View.INVISIBLE
                                binding.emptyS.visibility = View.VISIBLE
                            } else {
                                binding.linS.visibility = View.VISIBLE
                                binding.linContentS.visibility = View.VISIBLE
                                binding.emptyS.visibility = View.GONE
                            }
                            binding.sCurrent.text = "$schoolNoticePage / ${result?.total}"
                            if (result?.data?.isNotEmpty() == true) {
                                var first = result?.data?.first()
                                binding.sTitle.text = first?.title
                                binding.sName.text = first?.username
                                binding.sTime.text = first?.release_time
                                binding.sContent.text = first?.content
                                if (first?.imgs is String) {
                                    GlideHelper.loadImage(binding.ivS, first.imgs.toString())

                                } else {
                                    var strings = first?.imgs as ArrayList<String>
                                    GlideHelper.loadImage(binding.ivS, strings.first())

                                }
                            }
                        } else {
                            Toast.makeText(this@MainActivity, obj.msg, Toast.LENGTH_SHORT)
                                .show()
                        }

                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }


            }

            override fun onFailure(call: Call<ResponseBody?>, t: Throwable) {

            }
        })

    }

    fun setSpanBold(text: String, view: TextView) {
        val spannableString = SpannableString(text)

        val boldSpan = StyleSpan(Typeface.BOLD)

        spannableString.setSpan(
            boldSpan,
            2,
            text.length - 1,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )

        view.text = spannableString

    }

    private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action == Intent.ACTION_TIME_TICK) {
                binding.tvTime.text = getHM()
            } else if (action == Intent.ACTION_DATE_CHANGED) {
                autoConfig()
            }
        }
    }
    var dayOfWeek = ""
    fun getHM(): String {
        val currentDate = Date(System.currentTimeMillis())
        val dateFormat = SimpleDateFormat("HH:mm")
        val dateFormatDay = SimpleDateFormat("yyyy-MM-dd")
        val dayFormat = SimpleDateFormat("EEEE", Locale.getDefault())
        dayOfWeek = dayFormat.format(currentDate)
        val day = dateFormatDay.format(currentDate)
        val time = dateFormat.format(currentDate)
        return "$time $dayOfWeek\n$day"
    }

    fun monClick(v: View) {
        when (v.id) {
            R.id.lin_work -> {
                var token = MMKV.defaultMMKV().decodeString("token")
                if (token.isNullOrEmpty()) {
                    ToastUtils.showShort("请登录")
                    return
                }
                WorkHistoryFragment().show(supportFragmentManager, "")
            }


        }
    }

    fun refresh(v: View) {
        getHomeData()
    }

    private val PERMISSION_REQUEST_CODE = 1
    private val PERMISSIONS_REQUIRED = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.REQUEST_INSTALL_PACKAGES,
    )
    private val all = 2
    private val PERMISSIONS_ALL = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.REQUEST_INSTALL_PACKAGES,
    )

    fun door(v: View) {
        var token = MMKV.defaultMMKV().decodeString("token")
        if (token.isNullOrEmpty()) {
            ToastUtils.showShort("请登录")
            return
        }
        if (!hasPermissions(this, PERMISSIONS_REQUIRED)) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_REQUIRED, PERMISSION_REQUEST_CODE)
        } else {
            getTST()

        }
    }

    private fun hasPermissions(context: Context, permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    context,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "摄像头权限已授予", Toast.LENGTH_SHORT).show()
                getTST()
            } else {
                Toast.makeText(this, "摄像头权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        } else if (requestCode == 4) {
            updateApp()
        }
    }


}